package com.tianqu.tms.www.car.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.CarImage;
import com.tianqu.tms.www.car.actionform.CarImgInputActionForm;
import com.tianqu.tms.www.car.viewhelper.CarStockModifyViewhelper;

/**
 * @author zhangxueliang 对图片进行上传和确认操作
 */
public class CarImageResultAction extends TmsAction {

	private Logger logger = Logger.getLogger(CarImageResultAction.class);
	private static final String IMGTYPE = "imgType";// 1：车辆整体图片
	private static final String IMGKEY = "imgKey";// 图片位置key
	private static final String IMGLIST = "imgList";// 用于存放图片对象的list
	private static final String SEEPIC = "seePic";
	private static final String UPPIC = "upPic";
	private static final String IMAGEERROR = "imageError";

	@SuppressWarnings("unchecked")
	@Override
	protected ActionForward doAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response, UserContext uc) throws Exception {

		String imgType = (String) uc.getAttribute(IMGTYPE);
		String imgKey = (String) uc.getAttribute(IMGKEY);
		String forward = "";

		// 从form中
		CarImgInputActionForm carImgForm = (CarImgInputActionForm) form;
		CarStockModifyViewhelper viewhelp = (CarStockModifyViewhelper) uc.getAttribute(TmsConstants.VIEWHELP);
		viewhelp.setIsImageBack(1);
		if (carImgForm.getBackButton() != null) {
			viewhelp.setSeePicFlag(false);
			uc.setAttribute(TmsConstants.VIEWHELP, viewhelp);
			request.setAttribute(TmsConstants.VIEWHELP, uc.getAttribute(TmsConstants.VIEWHELP));
			carImgForm.setBackButton(null);
			viewhelp.setImageFlag("0");
			forward = UPPIC;
		} else {
			// 显示图片的button
			if (carImgForm.getSeePicButton() != null) {
				// String imgPath = carImgForm.getImgPath();
				FormFile formfil = carImgForm.getImgPath();
				/** 判断图片后缀名是否正常 **/
				// 判断图片是否正确
				if (imageAll(formfil)) {
					setErrorsToRequest(request, TmsConstants.I0015, null);
					viewhelp.setImageFlag("0");
					uc.setAttribute(TmsConstants.VIEWHELP, viewhelp);
					request.setAttribute(TmsConstants.VIEWHELP, uc.getAttribute(TmsConstants.VIEWHELP));
					return mapping.findForward(IMAGEERROR);
				} else if (formfil.getFileSize() > 1048576) {
					setErrorsToRequest(request, TmsConstants.I0018, null);
					viewhelp.setImageFlag("0");
					uc.setAttribute(TmsConstants.VIEWHELP, viewhelp);
					request.setAttribute(TmsConstants.VIEWHELP, uc.getAttribute(TmsConstants.VIEWHELP));
					return mapping.findForward(IMAGEERROR);
				}
				viewhelp.setImageFlag("1");
				// 生成图片
				String img = System.currentTimeMillis() + ".jpg";// 图片名称
				try {
					// 文件路径
					String path =ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOADTMP_CONTEXT_ROOT_KEY));
					FileOutputStream fileOutput = new FileOutputStream(new File(path +  img));
					fileOutput.write(formfil.getFileData());
					fileOutput.flush();

					// 压缩
					// FileInputStream in = new FileInputStream(new
					// File(path+"/"+img));
					// FileOutputStream out = new FileOutputStream(new
					// File(path+"/"+img) );
					// ImageUtils. resizeJpg(in, out, 640, 640, 0.85f, new
					// String[] {}, ImageUtils.FONT, ImageUtils.FONT_COLOR);
				} catch (Exception e) {
					logger.error("carImageResultAction upload error.", e);
				}

				//
				viewhelp.setSeePic(ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.UPLOADTMP_CONTEXT_ROOT_KEY) + img));
				// 前台显示出隐藏部分的图片
				viewhelp.setSeePicFlag(true);
				uc.setAttribute(TmsConstants.VIEWHELP, viewhelp);
				// 返回当前页面 要对form的值重新set
				carImgForm.setSeePicButton(null);
				request.setAttribute(TmsConstants.VIEWHELP, viewhelp);
				forward = SEEPIC;
			} else {

				// 把一组数据打包存如entity中
				CarImage entity = CarImage.getInstance();
				entity.setImgKey(imgKey);
				entity.setImgType(imgType);
				entity.setImgPath(viewhelp.getSeePic());// 这个Path需要处理一下
				if ("1".equals(imgKey)) {
					viewhelp.setImg1(viewhelp.getSeePic());
				} else if ("2".equals(imgKey)) {
					viewhelp.setImg2(viewhelp.getSeePic());
				} else if ("3".equals(imgKey)) {
					viewhelp.setImg3(viewhelp.getSeePic());
				} else if ("4".equals(imgKey)) {
					viewhelp.setImg4(viewhelp.getSeePic());
				} else if ("5".equals(imgKey)) {
					viewhelp.setImg5(viewhelp.getSeePic());
				} else if ("6".equals(imgKey)) {
					viewhelp.setImg6(viewhelp.getSeePic());
				} else if ("7".equals(imgKey)) {
					viewhelp.setImg7(viewhelp.getSeePic());
				} else if ("8".equals(imgKey)) {
					viewhelp.setImg8(viewhelp.getSeePic());
				}
				// 前台不显示隐藏部分的图片
				viewhelp.setSeePicFlag(false);
				// 放到一个list中，每次存的时候往里面ADD一下就可以了
				viewhelp.setImageFlag("0");
				uc.removeAttribute(IMGTYPE);
				uc.removeAttribute(IMGKEY);
				request.setAttribute(TmsConstants.VIEWHELP, uc.getAttribute(TmsConstants.VIEWHELP));
				forward = UPPIC;

			}
		}

		return mapping.findForward(forward);
	}

	/***
	 * 图片名称验证
	 */
	public boolean imageAll(FormFile file) {
		int i = 0;
		String type = file.getFileName();
		if (type.length() == 0)
			return true;
		while (i != -1) {
			// 找到上传文件的类型的位置，这个地方的是'.'
			i = type.indexOf(".");
			/* 截取上传文件的后缀名,此时得到了文件的类型 */
			type = type.substring(i + 1).toLowerCase();
		}
		if (!type.equals("jpg") && !type.equals("jpeg")) {
			return true;
		} else {
			return false;
		}
	}
}
